﻿using System;
using System.Linq;
using System.Text;
using System.Collections.Generic;

using LeanEngine.Entity;

namespace LeanEngine.Data.Linq.Language
{
    public sealed class TableToken : IQueryToken
    {
        #region Declaration Members

        private static byte _instanceCount;

        #endregion

        #region Constructor Members

        public TableToken(MetaTable table)
        {
            this.Metadata = table;
            this.Alias = "t" + _instanceCount++.ToString();
            this.Name = table.TableName;            

            this.Columns = (from c in table.ColumnsList
                           select new ColumnToken(this) 
                            { 
                                Name = c.DBColumn.Name, 
                                PropertyName = c.PropertyName 
                            }).ToList();
        }

        public TableToken(string customName, TableToken leftTable, TableToken rightTable)
        {
            this.Alias = "t" + _instanceCount++.ToString();
            this.Name = customName;

            this.Columns = new List<ColumnToken>();
            foreach (var column in leftTable.Metadata.ColumnsList.WherePrimaryKey())
            {
                this.Columns.Add(new ColumnToken(this)
                    {
                        Name = column.DBColumn.Name,
                        PropertyName = column.PropertyName
                    });
            }

            foreach (var column in rightTable.Metadata.ColumnsList.WherePrimaryKey())
            {
                this.Columns.Add(new ColumnToken(this)
                {
                    Name = column.DBColumn.Name,
                    PropertyName = column.PropertyName
                });
            }
        }

        #endregion

        #region PropertyInfo Members

        public string Name { get; private set; }
        public string Alias { get; private set; }
        public MetaTable Metadata { get; private set; }
        public List<ColumnToken> Columns { get; private set; }

        #endregion

        #region ILanguageToken Members

        public string GetStatement()
        {
            return string.IsNullOrEmpty(this.Alias) ? this.Name : this.Alias + "." + this.Name;
        }

        #endregion
    }
}
